package com.hui.wanxin.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hui.wanxin.web.entity.Dictionary;
import com.hui.wanxin.web.entity.PopularScience;
import com.hui.wanxin.web.mapper.PopularScienceMapper;
import com.hui.wanxin.web.service.DictionaryService;
import com.hui.wanxin.web.service.PopularScienceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 灰灰
 * @since 2023-10-13
 */
@Service
public class PopularScienceServiceImpl extends ServiceImpl<PopularScienceMapper, PopularScience> implements PopularScienceService {

    @Autowired
    private DictionaryService dictionaryService;

    @Override
    public Page<PopularScience> listByPage(PopularScience popularScience) {
        Page<PopularScience> page = lambdaQuery()
                .eq(popularScience.getTitle() != null, PopularScience::getTitle, popularScience.getTitle())
                .eq(popularScience.getMenu() != null, PopularScience::getMenu, popularScience.getMenu())
                .eq(popularScience.getType() != null, PopularScience::getMenu, popularScience.getType())
                .like(popularScience.getTheKey() != null, PopularScience::getTheKey, popularScience.getTheKey())
                .page(new Page<PopularScience>(popularScience.getPageNumber(), popularScience.getPageSize()));
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(PopularScience popularScience) {
        //保存字典
        List<Dictionary> dictionaryList = dictionaryService.lambdaQuery().list();
        String theKey = popularScience.getTheKey();
        List<String> split = new ArrayList<>();
        if (theKey.contains("，")) {
            split = Arrays.asList(theKey.split("，"));
        }
        if (theKey.contains(",")) {
            split = Arrays.asList(theKey.split(","));
        }
        List<Dictionary> saveDictionaryList = new ArrayList<>();
        if (CollUtil.isNotEmpty(dictionaryList)) {
            List<String> dList = dictionaryList.stream().map(Dictionary::getWork).collect(Collectors.toList());
            split = split.stream().filter(x->dList.stream().anyMatch(dItem -> dItem.equals(x))).collect(Collectors.toList());
        }
        for (String s : split) {
            Dictionary dictionary = new Dictionary();
            dictionary.setWork(s);
            saveDictionaryList.add(dictionary);
        }
        return save(popularScience)&&  dictionaryService.saveBatch(saveDictionaryList);
    }
}
